package inftel.android.googlemaps;


import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;


public class GoogleMaps extends MapActivity {
	private MapView mapView;
	private LocationManager locationManager;
	List<Overlay> mapOverlays;
	Drawable drawable;
	public int ayuda=0;
	ItemizedOverlay itemizedOverlayTesoro;
	ItemizedOverlay itemizedOverlayPosicion;
	ItemizedOverlay itemizedOverlayplayer1;
	ItemizedOverlay player2;
	private Road mRoad;
	public double flat;
	public double flon;
	public int longitudTesoro;
	public int latitudTesoro;
	public int posicionJugadores []=new int [4];
	
	private String nombre;
	private int p1;
	private int p2;
	
	private Bundle bund;
	
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE, 1, 2, R.string.salir);
        menu.add(Menu.NONE, 2, 1, R.string.ayudaOn);
        return true;
	}
	
	 @Override
	 public boolean onMenuItemSelected(int featureId, MenuItem item) {
	  super.onMenuItemSelected(featureId, item);
	        switch(item.getItemId()) {
	        
	        case 1:
	            setResult(RESULT_OK);
	            finish();
	            break;
	        case 2:
	        	setResult(RESULT_OK);
	        	ayuda=1;
	        	break;	            
	        }
	        return true;
	 }
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.main); // bind the layout to the activity
		
	bund = this.getIntent().getExtras();
		
		// create a map view
		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapView.setSatellite(true);
		mapView.getController();
		
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, new GeoUpdateHandler());
		
		//Acceder a base de datos para obtener coordenadas tesoro
		latitudTesoro = 37876572;
		longitudTesoro = -4795167;
		posicionJugadores[0]=-1;
		posicionJugadores[1]=-1;
		pintaTesoro(latitudTesoro, longitudTesoro);
		
	}
	
	public void pintaTesoro (int latitud, int longitud)
	{
		

		
		mapOverlays = mapView.getOverlays();
		drawable = this.getResources().getDrawable(R.drawable.androidmarker);
		itemizedOverlayTesoro = new ItemizedOverlay(drawable);
		
		//GeoPoint point = new GeoPoint(lat, lng);
		GeoPoint tesoro = new GeoPoint(latitud, longitud);
		
		OverlayItem overlayTesoro = new OverlayItem(tesoro,"","");
		
		itemizedOverlayTesoro.addOverlay(overlayTesoro);
		mapOverlays.add(itemizedOverlayTesoro);
		//mapController.setCenter(tesoro);
	}
	
	public void pintaPosicion (int latitud, int longitud, int player)
	{
		if (player==0){
		
	
		mapOverlays = mapView.getOverlays();
		drawable = this.getResources().getDrawable(R.drawable.ballena);
		
		itemizedOverlayPosicion = new ItemizedOverlay(drawable);
		
		//GeoPoint point = new GeoPoint(lat, lng);
		GeoPoint tesoro = new GeoPoint(latitud, longitud);
		OverlayItem overlayTesoro = new OverlayItem(tesoro,"","");
		itemizedOverlayPosicion.addOverlay(overlayTesoro);
		
		mapOverlays.add(itemizedOverlayPosicion);
		
		
		//mapController.setCenter(tesoro);
		}
		else{			
		
				mapOverlays = mapView.getOverlays();
				drawable = this.getResources().getDrawable(R.drawable.eu);
				
				itemizedOverlayplayer1 = new ItemizedOverlay(drawable);
				
				//GeoPoint point = new GeoPoint(lat, lng);
				GeoPoint tesoro = new GeoPoint(latitud, longitud);
				
				OverlayItem overlayTesoro = new OverlayItem(tesoro,"","");
				
				itemizedOverlayplayer1.addOverlay(overlayTesoro);
				mapOverlays.add(itemizedOverlayplayer1);
				
				//mapController.setCenter(tesoro);
		}
		
	}
	
	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			TextView textView = (TextView) findViewById(R.id.description);
			textView.setText(mRoad.mName + " " + mRoad.mDescription);
			MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
			List<Overlay> listOfOverlays = mapView.getOverlays();
			listOfOverlays.clear();
			listOfOverlays.add(mapOverlay);
			mapView.invalidate();
		}
	};

	
	private InputStream getConnection(String url) {
		InputStream is = null;
		try {
			URLConnection conn = new URL(url).openConnection();
			is = conn.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public class GeoUpdateHandler implements LocationListener {

		@Override
		public void onLocationChanged(Location location) {
			
			nombre = bund.getString("NOMBRE");
			
			Log.i("-------Nombre", nombre);
					        
		        //Construimos el mensaje a mostrar
		      //
					
			int lat = (int) (location.getLatitude() * 1E6);
			int lng = (int) (location.getLongitude() * 1E6);
			

			String servletURL = "http://192.168.183.68:8080/CentralEnBuscaLaBallena-war/EnviarLocalizacionJugadorServlet";
			
			try {

				URL ob = new URL(servletURL + "?usuario=" + nombre + "&latitud=" + lat + "&longitud=" + lng);

				URLConnection conn = ob.openConnection();

				conn.setDoInput(true);
				conn.setDoOutput(true);
				
				Log.i("-------URL", ob.toString());
				
				InputStream in = conn.getInputStream();
				DataInputStream dos = new DataInputStream(in);
				String leido = dos.readLine();
				


			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			
			
			String servletURL2 = "http://192.168.183.68:8080/CentralEnBuscaLaBallena-war/PosicionJugadorServlet";
			
			try {

				URL ob2 = new URL(servletURL2 + "?usuario=" + "manolo");

				URLConnection conn2 = ob2.openConnection();

				conn2.setDoInput(true);
				conn2.setDoOutput(true);
				
				Log.i("-------URL", ob2.toString());
				
				InputStream in = conn2.getInputStream();
				DataInputStream dos = new DataInputStream(in);
				String leido1 = dos.readLine();
				String leido2 = dos.readLine();
				
				p1 = Integer.parseInt(leido1);
			    p2 =  Integer.parseInt(leido2);
			    
			    
			    Log.i("-------Latitud", leido1);
			    Log.i("-------Longitud", leido2);
			


			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
	
			GeoPoint point = new GeoPoint(lat, lng);
			drawable = mapView.getResources().getDrawable(R.drawable.ballena);
			itemizedOverlayPosicion = new ItemizedOverlay(drawable);
			flat = location.getLatitude();
			flon = location.getLongitude();
			if (ayuda==1)
			{
			new Thread() {
				@Override
				public void run() {
					double fromLat = flat, fromLon = flon, toLat = latitudTesoro/1E6, toLon = longitudTesoro / 1E6;
					String url = RoadProvider.getUrl(fromLat, fromLon, toLat,
							toLon);
					InputStream is = getConnection(url);
					
					mRoad = RoadProvider.getRoute(is);
					mHandler.sendEmptyMessage(0);
				}
			}.start();
			}
			
			if (Math.abs(((latitudTesoro/1E6)-flat))<=0.0001 && Math.abs(((longitudTesoro/1E6)-flon))<=0.0001)
			{
				Toast.makeText(getApplicationContext(), "Tesoro encontrado",100).show();
			}

			// "http://localhost:8080/ObtenerDestinosServlet?partida=inftel&equipo=1"
			//Log.i("sixe",String.valueOf(mapOverlays.size()));
			new Thread() {
				@Override
				public void run() {
					mapOverlays.clear();
					pintaTesoro(latitudTesoro, longitudTesoro);
					pintaPosicion((int)(flat*1E6),(int)(flon*1E6),0);
					
					
					pintaPosicion(p1, p2, 1);
										
					
					
				}
			}.start();
			
			//mapController.setZoom(18);
			//mapController.setCenter(point);
		}
		
		@Override
		public void onProviderDisabled(String provider) {
		}
		

		@Override
		public void onProviderEnabled(String provider) {
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}
	
	class MapOverlay extends com.google.android.maps.Overlay {
		Road mRoad;
		ArrayList<GeoPoint> mPoints;

		public MapOverlay(Road road, MapView mv) {
			mRoad = road;
			if (road.mRoute.length > 0) {
				mPoints = new ArrayList<GeoPoint>();
				for (int i = 0; i < road.mRoute.length; i++) {
					mPoints.add(new GeoPoint((int) (road.mRoute[i][1] * 1000000),
							(int) (road.mRoute[i][0] * 1000000)));
				}
				int moveToLat = (mPoints.get(0).getLatitudeE6() + (mPoints.get(
						mPoints.size() - 1).getLatitudeE6() - mPoints.get(0)
						.getLatitudeE6()) / 2);
				int moveToLong = (mPoints.get(0).getLongitudeE6() + (mPoints.get(
						mPoints.size() - 1).getLongitudeE6() - mPoints.get(0)
						.getLongitudeE6()) / 2);
				GeoPoint moveTo = new GeoPoint(moveToLat, moveToLong);

				MapController mapController = mv.getController();
				//mapController.animateTo(moveTo);
				//mapController.setZoom(18);
			}
		}
		
 
		@Override
		public boolean onTouchEvent(MotionEvent event, MapView mapView) 
        {   
			
            if (event.getAction()==1) {                
                GeoPoint p = mapView.getProjection().fromPixels(
                    (int) event.getX(),
                    (int) event.getY());
                Log.i("x",String.valueOf(event.getX()));
                    Toast.makeText(getBaseContext(), 
                        p.getLatitudeE6() / 1E6 + "," + 
                        p.getLongitudeE6() /1E6 , 
                        Toast.LENGTH_SHORT).show();
            }                            
            return false;
        }        

		@Override
		public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) {
			super.draw(canvas, mv, shadow);
			drawPath(mv, canvas);
			return true;
		}

		public void drawPath(MapView mv, Canvas canvas) {
			int x1 = -1, y1 = -1, x2 = -1, y2 = -1;
			Paint paint = new Paint();
			paint.setColor(Color.RED);
			paint.setStyle(Paint.Style.FILL_AND_STROKE);
			paint.setStrokeWidth(3);
			for (int i = 0; i < mPoints.size(); i++) {
				Point point = new Point();
				mv.getProjection().toPixels(mPoints.get(i), point);
				x2 = point.x;
				y2 = point.y;
				if (i > 0) {
					canvas.drawLine(x1, y1, x2, y2, paint);
				}
				x1 = x2;
				y1 = y2;
			}
		}
	}
}